<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Jedrzej\Pimpable\PimpableTrait;

class OperationLog extends Model
{
    use HasFactory, PimpableTrait;

    const UPDATED_AT = null;

    // 可批量赋值的字段
    protected $fillable = ['user_id', 'ip', 'path', 'method', 'content', 'describe'];

    // 转换属性
    protected $casts = [
        'created_at' => 'date:Y-m-d H:i:s'
    ];

    // 可搜索的字段
    protected $searchable = ['created_at', 'user_id'];

    // 设置默认排序字段
    protected $defaultSortCriteria = ['id,desc'];

    // 指定搜索关键字
    protected $sortParameterName = 'sortBy';

    /**
     * 设置修改器
     *
     * @param $value
     */
    public function setContentAttribute($value)
    {
        $this->attributes['content'] = json_encode($value);
    }

    /**
     * 设置访问器
     *
     * @param $valie
     * @return mixed
     */
    public function getContentAttribute($valie)
    {
        return json_decode($valie, true);
    }

    /**
     * 和用户的关联
     *
     * @return BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}
